package com.nxmu.hire.controller;

import com.github.pagehelper.PageInfo;
import com.nxmu.hire.common.exception.ServiceException;
import com.nxmu.hire.common.util.ResponseResult;
import com.nxmu.hire.model.Post;
import com.nxmu.hire.service.PostService;
import com.nxmu.hire.service.UserService;
import com.nxmu.hire.vo.AddPostReqVo;
import com.nxmu.hire.vo.FindPostListByPageReqVo;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.Objects;

@CrossOrigin(origins = "*",allowCredentials = "true")
@RestController
@RequestMapping("/post")
public class PostController {

    @Autowired
    private PostService postService;

    @Autowired
    private UserService userService;

    @ApiOperation(value = "添加教学岗位")
    @PostMapping(value = "/addPost")
    public ResponseResult addPost(@Valid @RequestBody AddPostReqVo addPostReqVo, HttpServletRequest request) {
        try {
            postService.addPost(addPostReqVo);
        } catch (ServiceException e) {
            return ResponseResult.fail(e.getMessage());
        }
        return ResponseResult.success();
    }

    @ApiOperation(value = "查询教学岗位")
    @PostMapping(value = "/findPostListByPage")
    public ResponseResult findPostListByPage(@Valid @RequestBody FindPostListByPageReqVo findPostListByPageReqVo) {
        if (Objects.isNull(findPostListByPageReqVo.getPageNum())) findPostListByPageReqVo.setPageNum(1);
        if (Objects.isNull(findPostListByPageReqVo.getPageSize())) findPostListByPageReqVo.setPageSize(100);
        if (!StringUtils.isEmpty(findPostListByPageReqVo.getUserId()) && Objects.isNull(findPostListByPageReqVo.getCollegeId()))
            findPostListByPageReqVo.setCollegeId(userService.findUserByUserId(findPostListByPageReqVo.getUserId()).getCollegeId());

        PageInfo<Post> postPageInfo = postService.findPostListByPage(findPostListByPageReqVo);
        return ResponseResult.success(postPageInfo);
    }

    @ApiOperation(value = "修改教学岗位数量")
    @GetMapping(value = "/modifyPostCount")
    public ResponseResult modifyPostCount(@RequestParam(name = "postId") Integer postId,@RequestParam(name = "postCount") Integer postCount) {
        try {
            postService.updatePostCountByPostId(postId,postCount);
        } catch (ServiceException e) {
            return ResponseResult.fail(e.getMessage());
        }
        return ResponseResult.success();
    }

}
